package com.changgou.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.service.WeixinPayService;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liyipeng
 * @date 2021-07-01 19:30
 */
@RestController
@RequestMapping(value = "/weixin/pay")
@CrossOrigin
public class WeixinPayController {

    @Autowired
    private WeixinPayService weixinPayService;

    @Autowired
    private Environment environment;

    /**
     * 创建二维码
     * @return
     */
    @RequestMapping("/create/native")
    public Result<Map<String, String>> createNative(@RequestParam Map<String, String> parameter) {
        //todo 从令牌中获取用户的名称
        String username="zhangsan";
        parameter.put("username",username);
        Map<String, String> map = weixinPayService.createNative(parameter);
        return new Result<Map<String, String>>(true, StatusCode.OK, "创建二维码成功", map);
    }




    /**
     * 查询支付状态
     * @param out_trade_no
     * @return
     */
    @GetMapping(value = "/status/query")
    public Result queryStatus(String out_trade_no){
        Map<String,String> resultMap = weixinPayService.queryPayStatus(out_trade_no);
        return new Result(true,StatusCode.OK,"查询状态成功！",resultMap);
    }

    @Value("${mq.pay.exchange.order}")
    private String exchange;
    @Value("${mq.pay.queue.order}")
    private String queue;
    @Value("${mq.pay.routing.key}")
    private String routing;


    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 用于接收微信传递过来的数据 通知地址 RequestMapping 中的值
     * 该链接是通过【统一下单API】中提交的参数notify_url设置 通知url必须为直接可访问的url，不能携带参数
     * @return
     */
    @RequestMapping("/notify/url")
    public String notifyurl(HttpServletRequest request) {
        ByteArrayOutputStream outputStream =null;
        ServletInputStream inputStream=null;
        System.out.println("==========微信回调了============");
        try {
            //1. 接收微信通知的数据流 读流
            inputStream = request.getInputStream();

            //2 将流转换成XML字符串  todo  写流
            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer,0,len);
            }
            byte[] bytes = outputStream.toByteArray();
            String xml = new String(bytes, "utf-8");
            System.out.println(xml);
            System.out.println("=================================");
            Map<String, String> map = WXPayUtil.xmlToMap(xml);
            System.out.println(map);
            //3.发送消息(orderid,支付时间，微信支付订单号，....)给rabbitmq

            //判断 获取到attach的值  判断值是否是1 或者2  如果是1 标识 普通的订单 如果是2 标识 秒杀的订单

            //{username:zhangsan,type:1}
            String attach = map.get("attach");
            Map<String,String> attachMap = JSON.parseObject(attach, Map.class);

            String type = attachMap.get("type");
            // 根据不同的值发送到不同的队列中
            switch (type){
                case "1":// 普通订单
                    rabbitTemplate.convertAndSend(exchange,routing, JSON.toJSONString(map));
                    break;
                case "2": //秒杀订单
                    rabbitTemplate.convertAndSend(
                            environment.getProperty("mq.pay.exchange.seckillorder"),
                            environment.getProperty("mq.pay.routing.seckillkey"),
                            JSON.toJSONString(map));
                    break;
                default:
                    System.out.println("你给的都不对");
                    break;
            }

            //4.返回给微信成功的响应
            Map respMap = new HashMap();
            respMap.put("return_code","SUCCESS");
            respMap.put("return_msg","OK");
            return WXPayUtil.mapToXml(respMap);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(outputStream!=null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(inputStream!=null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("接收到了数据了");
        //4.返回给微信成功的响应
        return null;
    }

    @GetMapping("/close")
    public Result closePay(Long id){
        try {
            weixinPayService.closePay(id);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("订单关闭异常");
        }
        return new Result(true, StatusCode.OK,"订单关闭成功");
    }

}
